// stores/circles.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
    getCircles,
    getCircleDetail,
    createCircle,
    updateCircle,
    deleteCircle,
    getHotCircles,
    searchCircles,
    getCircleStats,
    joinCircle,
    leaveCircle,
    getUserCircles,
    getCircleMembers,
    getCircleBatchStatus,
    removeCircleMember
} from '@/api/circle'

export const useCirclesStore = defineStore('circles', () => {
    const circles = ref([])
    const currentCircle = ref(null)
    const userCircles = ref([])
    const circleMembers = ref([])
    const loading = ref(false)
    const hasMore = ref(true)
    const page = ref(1)
    const pageSize = ref(5)

    // 获取圈子列表
    const fetchCirclesAction = async (params = {}) => {
        try {
            loading.value = true
            const response = await getCircles({
                page: page.value,
                pageSize: pageSize.value,
                ...params
            })

            if (response.code === 0) {
                if (params.page === 1 || !params.page) {
                    circles.value = response.data.list || response.data
                } else {
                    circles.value = [...circles.value, ...(response.data.list || response.data)]
                }

                // 检查是否还有更多数据
                hasMore.value = response.data.hasMore !== false &&
                    (response.data.list || response.data).length === pageSize.value

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        } finally {
            loading.value = false
        }
    }

    // 加载更多圈子
    const loadMoreCirclesAction = async (params = {}) => {
        if (!hasMore.value || loading.value) return

        page.value += 1
        return await fetchCirclesAction(params)
    }

    // 重置分页
    const resetPaginationAction = () => {
        page.value = 1
        hasMore.value = true
        circles.value = []
    }

    // 获取圈子详情
    const fetchCircleDetailAction = async (circleId) => {
        try {
            const response = await getCircleDetail(circleId)
            if (response.code === 0) {
                currentCircle.value = response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 创建圈子（仅管理员）
    const createCircleAction = async (circleData) => {
        try {
            const response = await createCircle(circleData)
            if (response.code === 0) {
                // 将新圈子添加到列表开头
                circles.value.unshift(response.data)
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 更新圈子信息（仅管理员）
    const updateCircleAction = async (circleId, updateData) => {
        try {
            const response = await updateCircle(circleId, updateData)
            if (response.code === 0) {
                // 更新本地圈子数据
                const index = circles.value.findIndex(circle => circle.circle_id === circleId)
                if (index !== -1) {
                    circles.value[index] = { ...circles.value[index], ...updateData }
                }

                if (currentCircle.value && currentCircle.value.circle_id === circleId) {
                    currentCircle.value = { ...currentCircle.value, ...updateData }
                }

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 删除圈子（仅管理员）
    const deleteCircleAction = async (circleId) => {
        try {
            const response = await deleteCircle(circleId)
            if (response.code === 0) {
                // 从本地列表中移除
                circles.value = circles.value.filter(circle => circle.circle_id !== circleId)

                if (currentCircle.value && currentCircle.value.circle_id === circleId) {
                    currentCircle.value = null
                }

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 获取热门圈子
    const fetchHotCirclesAction = async (limit = 5) => {
        try {
            const response = await getHotCircles(limit)
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 搜索圈子
    const searchCirclesAction = async (keyword, params = {}) => {
        try {
            const response = await searchCircles(keyword, params)
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 获取圈子统计信息（仅管理员）
    const fetchCircleStatsAction = async () => {
        try {
            const response = await getCircleStats()
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 用户加入圈子
    const joinCircleAction = async (circleId) => {
        try {
            const response = await joinCircle(circleId)
            if (response.code === 0) {
                // 更新本地圈子成员数量
                updateCircleMemberCount(circleId, 1)
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 用户退出圈子
    const leaveCircleAction = async (circleId) => {
        try {
            const response = await leaveCircle(circleId)
            if (response.code === 0) {
                // 更新本地圈子成员数量
                updateCircleMemberCount(circleId, -1)
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 更新圈子成员数量
    const updateCircleMemberCount = (circleId, change) => {
        // 更新圈子列表中的成员数量
        const circleIndex = circles.value.findIndex(circle => circle.circle_id === circleId)
        if (circleIndex !== -1) {
            const circle = circles.value[circleIndex]
            circle.member_count = Math.max(0, circle.member_count + change)
        }

        // 更新当前圈子的成员数量
        if (currentCircle.value && currentCircle.value.circle_id === circleId) {
            currentCircle.value.member_count = Math.max(0, currentCircle.value.member_count + change)
        }
    }

    // 获取用户加入的圈子列表
    const fetchUserCirclesAction = async (params = {}) => {
        try {
            const response = await getUserCircles(params)
            if (response.code === 0) {
                userCircles.value = response.data.list || response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 获取圈子的成员列表
    const fetchCircleMembersAction = async (circleId, params = {}) => {
        try {
            const response = await getCircleMembers(circleId, params)
            if (response.code === 0) {
                circleMembers.value = response.data.list || response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 批量获取用户与圈子的关系状态
    const fetchCircleBatchStatusAction = async (circleIds) => {
        try {
            const response = await getCircleBatchStatus(circleIds)
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 管理员移除圈子成员
    const removeCircleMemberAction = async (circleId, memberId) => {
        try {
            const response = await removeCircleMember(circleId, memberId)
            if (response.code === 0) {
                // 更新本地圈子成员数量
                updateCircleMemberCount(circleId, -1)

                // 从本地成员列表中移除该成员
                circleMembers.value = circleMembers.value.filter(member => member.user_id !== memberId)

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    return {
        circles,
        currentCircle,
        userCircles,
        circleMembers,
        loading,
        hasMore,
        page,
        pageSize,
        fetchCirclesAction,
        loadMoreCirclesAction,
        resetPaginationAction,
        fetchCircleDetailAction,
        createCircleAction,
        updateCircleAction,
        deleteCircleAction,
        fetchHotCirclesAction,
        searchCirclesAction,
        fetchCircleStatsAction,
        joinCircleAction,
        leaveCircleAction,
        fetchUserCirclesAction,
        fetchCircleMembersAction,
        fetchCircleBatchStatusAction,
        removeCircleMemberAction
    }
})